package com.briup.ch11;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;

/**
 * @Author briup-adam
 * @Date 2023/10/24 下午4:46
 * @Description
 * @see java.io.RandomAccessFile
 **/

public class RandomAccessFileDemo {
    /**
     * 替换指定位置上的字节
     * @param path 文件路径好
     * @param pos  指定位置
     * @throws Exception
     */
    public static  void  replace(String path,long pos) throws Exception {
        //先创建文件对象
        File file = new File(path);

        RandomAccessFile rw=null;
        rw=new RandomAccessFile(file,"rw");
        //跳转到指定字节后
//        rw.seek(pos);
        rw.seek(file.length());
        //写入内容
        rw.write("bruip".getBytes());

        rw.close();

    }
    public static void  insert(String path,long pos,String content) throws Exception {
        File file = new File(path);
        RandomAccessFile rw=new RandomAccessFile(file,"rw");
        rw.seek(pos);
        byte [] b=new byte[(int)(file.length()-pos)];
        rw.read(b);
        rw.seek(pos);
        rw.write(content.getBytes());
        rw.write(b);
        rw.close();

    }

    public static void main(String[] args) {
        try {
            replace("02code/src/file.txt",6);
            insert("02code/src/file.txt",6,"青梅绕床生，郎骑竹马来");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
